package com.laicunba.event.listener;

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import com.laicunba.event.JzhRepaymentEvent;
import com.laicunba.pojo.FinancingTargetBidDO;
import com.laicunba.pojo.FinancingTargetDO;
import com.laicunba.pojo.TemplateDO;
import com.laicunba.pojo.UserDO;
import com.laicunba.service.FinancingTargetBidService;
import com.laicunba.service.FinancingTargetService;
import com.laicunba.service.MobileMessageService;
import com.laicunba.service.TemplateService;
import com.laicunba.service.UserService;
import com.laicunba.util.StringUtil;

@Component
public class JzhRepaymentListener implements ApplicationListener<JzhRepaymentEvent> {
	@Autowired
	private FinancingTargetBidService financingTargetBidService;
	@Autowired
	private TemplateService templateService;
	@Autowired
	private UserService userService;
	@Autowired
	private MobileMessageService mobileMessageService;
	@Autowired
	private FinancingTargetService financingTargetService;

	private static TemplateDO MSG_TMPLATE;
	private static MathContext MC = new MathContext(2, RoundingMode.HALF_DOWN);

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public void onApplicationEvent(JzhRepaymentEvent event) {
		String bid = (String) event.getSource();
		if (StringUtil.isEmpty(bid)) {
			return;
		}
		FinancingTargetBidDO financingTargetBidDO = financingTargetBidService.get(FinancingTargetBidDO.class, bid);
		if (financingTargetBidDO == null) {
			return;
		}
		if (MSG_TMPLATE == null) {
			MSG_TMPLATE = templateService.findByCodeWidthDefault("JZH_REPAYMENT");
		}

		FinancingTargetDO targetDO = financingTargetService.get(FinancingTargetDO.class, financingTargetBidDO.getFinancingTargetId());
		Map param = new HashMap();
		param.put("targetName", targetDO.getName());
		param.put("Principal", financingTargetBidDO.getWithdrawPrincipal());
		BigDecimal profit = financingTargetBidDO.getWithdrawProfit();
		if (financingTargetBidDO.getExpireSendProfit() != null) {
			profit = profit.add(financingTargetBidDO.getExpireSendProfit());
		}
		param.put("Profit", profit);
		param.put("Amount", financingTargetBidDO.getWithdrawPrincipal().add(profit));
		String msg = templateService.simpleMerge(MSG_TMPLATE.getContent(), param);
		UserDO userDO = userService.get(UserDO.class, financingTargetBidDO.getBidUserId());
		if (userDO == null) {
			return;
		}
		mobileMessageService.sendMsgAsync(userDO.getMobile(), msg);
	}

}
